import { Metadata } from 'next';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Progress } from '@/components/ui/progress';
import {
  SolutionsBreadcrumb,
  SolutionsNavigationSimple,
} from '@/components/solutions-navigation';
import { CaseStudies, caseStudiesByIndustry } from '@/components/case-studies';
import {
  CreditCard,
  Zap,
  Activity,
  AlertTriangle,
  BarChart3,
  RefreshCw,
  CheckCircle,
} from 'lucide-react';

export const metadata: Metadata = {
  title: '实时支付处理解决方案 | CActor金融科技',
  description:
    'CActor实时支付系统：流处理架构、背压控制、故障恢复的高性能支付解决方案',
};

/**
 * 实时支付处理解决方案页面
 * 展示CActor在实时支付处理领域的完整技术方案
 */
export default function RealTimePaymentPage() {
  const performanceMetrics = [
    { label: '处理延迟', value: '< 100ms', progress: 95 },
    { label: '吞吐量', value: '50K TPS', progress: 92 },
    { label: '成功率', value: '99.95%', progress: 99 },
    { label: '故障恢复', value: '< 5s', progress: 94 },
  ];

  const streamComponents = [
    {
      name: '支付流入口Actor',
      description: '支付请求接收和预处理',
      icon: CreditCard,
      color: 'bg-blue-500',
      features: ['请求验证', '限流控制', '路由分发'],
    },
    {
      name: '流处理引擎Actor',
      description: '实时支付流处理核心',
      icon: Activity,
      color: 'bg-green-500',
      features: ['流式计算', '状态管理', '窗口聚合'],
    },
    {
      name: '背压控制Actor',
      description: '系统负载均衡和背压管理',
      icon: BarChart3,
      color: 'bg-yellow-500',
      features: ['负载监控', '流量控制', '缓冲管理'],
    },
    {
      name: '故障恢复Actor',
      description: '异常处理和自动恢复',
      icon: RefreshCw,
      color: 'bg-red-500',
      features: ['故障检测', '自动重试', '降级处理'],
    },
  ];

  const paymentFlow = [
    {
      step: 1,
      title: '支付请求',
      description: '接收支付指令',
      icon: CreditCard,
    },
    {
      step: 2,
      title: '风险评估',
      description: '实时风险检查',
      icon: AlertTriangle,
    },
    {
      step: 3,
      title: '资金验证',
      description: '账户余额验证',
      icon: CheckCircle,
    },
    { step: 4, title: '交易执行', description: '执行资金转移', icon: Zap },
    { step: 5, title: '状态通知', description: '结果实时推送', icon: Activity },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-50 to-pink-100 dark:from-slate-900 dark:to-slate-800">
      {/* Breadcrumb */}
      <div className="max-w-7xl mx-auto px-4 pt-6">
        <SolutionsBreadcrumb />
      </div>

      {/* Hero Section */}
      <section className="relative py-20 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <Badge variant="outline" className="mb-4">
              <CreditCard className="mr-2 h-4 w-4" />
              实时支付处理解决方案
            </Badge>
            <h1 className="text-4xl md:text-6xl font-bold mb-6 bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
              高性能支付流处理
            </h1>
            <p className="text-xl text-muted-foreground mb-8 max-w-3xl mx-auto">
              基于CActor流处理架构的实时支付系统，提供毫秒级响应、智能背压控制和自动故障恢复能力
            </p>
          </div>

          {/* Performance Metrics */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-16">
            {performanceMetrics.map((metric, index) => (
              <Card
                key={index}
                className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0"
              >
                <CardHeader className="pb-2">
                  <CardTitle className="text-2xl font-bold text-purple-600">
                    {metric.value}
                  </CardTitle>
                  <CardDescription>{metric.label}</CardDescription>
                </CardHeader>
                <CardContent>
                  <Progress value={metric.progress} className="h-2" />
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Payment Processing Flow */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">支付处理流程</h2>
            <p className="text-lg text-muted-foreground">
              端到端的实时支付处理管道
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-5 gap-6 mb-12">
            {paymentFlow.map((item, index) => {
              const IconComponent = item.icon;
              return (
                <div key={index} className="text-center">
                  <div className="bg-purple-500 text-white rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
                    <IconComponent className="h-8 w-8" />
                  </div>
                  <div className="bg-white dark:bg-slate-800 p-4 rounded-lg shadow-sm">
                    <h4 className="font-semibold mb-2">{item.title}</h4>
                    <p className="text-sm text-muted-foreground">
                      {item.description}
                    </p>
                  </div>
                  {index < paymentFlow.length - 1 && (
                    <div className="hidden md:block absolute translate-x-20 translate-y-8">
                      <div className="w-8 h-0.5 bg-purple-300"></div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Stream Architecture */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">流处理架构</h2>
            <p className="text-lg text-muted-foreground">
              基于Actor模型的分布式流处理引擎
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            {streamComponents.map((component, index) => {
              const IconComponent = component.icon;
              return (
                <Card
                  key={index}
                  className="group hover:shadow-lg transition-all duration-300 bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0"
                >
                  <CardHeader>
                    <div className="flex items-center gap-4 mb-4">
                      <div
                        className={`p-3 rounded-lg ${component.color} text-white`}
                      >
                        <IconComponent className="h-6 w-6" />
                      </div>
                      <div>
                        <CardTitle className="text-xl">
                          {component.name}
                        </CardTitle>
                        <CardDescription>
                          {component.description}
                        </CardDescription>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-2">
                      {component.features.map((feature, idx) => (
                        <Badge key={idx} variant="outline" className="text-xs">
                          {feature}
                        </Badge>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      </section>

      {/* Technical Implementation */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <Tabs defaultValue="stream-processing" className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="stream-processing">流处理</TabsTrigger>
              <TabsTrigger value="backpressure">背压控制</TabsTrigger>
              <TabsTrigger value="fault-tolerance">故障恢复</TabsTrigger>
              <TabsTrigger value="monitoring">监控优化</TabsTrigger>
            </TabsList>

            <TabsContent value="stream-processing" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle>流处理引擎实现</CardTitle>
                  <CardDescription>基于Actor的高性能流处理核心</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="bg-slate-900 text-green-400 p-6 rounded-lg font-mono text-sm overflow-x-auto">
                    <pre>{`// 支付流处理Actor实现
class PaymentStreamActor extends CActor {
  constructor() {
    super()
    this.streamBuffer = new CircularBuffer(10000)
    this.windowState = new Map()
    this.metrics = new MetricsCollector()
  }

  // 处理支付流事件
  async handlePaymentEvent(event: PaymentEvent): Promise<void> {
    const startTime = Date.now()
    
    try {
      // 1. 事件验证和预处理
      const validatedEvent = await this.validateEvent(event)
      
      // 2. 状态更新和窗口计算
      await this.updateWindowState(validatedEvent)
      
      // 3. 业务规则处理
      const processedEvent = await this.applyBusinessRules(validatedEvent)
      
      // 4. 下游传播
      await this.propagateToDownstream(processedEvent)
      
      // 5. 指标收集
      this.metrics.recordProcessingTime(Date.now() - startTime)
      this.metrics.incrementProcessedCount()
      
    } catch (error) {
      await this.handleProcessingError(event, error)
    }
  }

  // 窗口状态管理
  async updateWindowState(event: PaymentEvent): Promise<void> {
    const windowKey = this.getWindowKey(event.timestamp)
    const window = this.windowState.get(windowKey) || new PaymentWindow()
    
    window.addEvent(event)
    
    // 检查窗口是否完成
    if (window.isComplete()) {
      const aggregatedResult = window.aggregate()
      await this.send('aggregation-actor', {
        type: 'WINDOW_COMPLETE',
        result: aggregatedResult
      })
      
      this.windowState.delete(windowKey)
    } else {
      this.windowState.set(windowKey, window)
    }
  }

  // 背压检测和处理
  async checkBackpressure(): Promise<boolean> {
    const bufferUtilization = this.streamBuffer.utilization()
    const processingLatency = this.metrics.getAverageLatency()
    
    if (bufferUtilization > 0.8 || processingLatency > 200) {
      await this.send('backpressure-controller', {
        type: 'BACKPRESSURE_DETECTED',
        severity: this.calculateSeverity(bufferUtilization, processingLatency)
      })
      return true
    }
    
    return false
  }
}`}</pre>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="backpressure" className="mt-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <BarChart3 className="h-5 w-5" />
                      背压检测机制
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="bg-yellow-50 dark:bg-yellow-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">实时监控指标</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 缓冲区利用率监控</li>
                          <li>• 处理延迟趋势分析</li>
                          <li>• 吞吐量变化检测</li>
                          <li>• 内存使用率监控</li>
                        </ul>
                      </div>
                      <div className="bg-red-50 dark:bg-red-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">阈值配置</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 缓冲区：80% 触发警告</li>
                          <li>• 延迟：200ms 触发限流</li>
                          <li>• 内存：90% 触发清理</li>
                        </ul>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Activity className="h-5 w-5" />
                      背压控制策略
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">流量控制</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 动态限流算法</li>
                          <li>• 优先级队列管理</li>
                          <li>• 批处理优化</li>
                          <li>• 负载均衡调整</li>
                        </ul>
                      </div>
                      <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">资源管理</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 内存池动态扩展</li>
                          <li>• 线程池自适应调整</li>
                          <li>• 缓存策略优化</li>
                        </ul>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </TabsContent>

            <TabsContent value="fault-tolerance" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <RefreshCw className="h-5 w-5" />
                    故障恢复策略
                  </CardTitle>
                  <CardDescription>
                    多层次的故障检测和自动恢复机制
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div className="text-center">
                      <div className="bg-red-100 dark:bg-red-900 p-4 rounded-lg mb-4">
                        <AlertTriangle className="h-8 w-8 mx-auto text-red-600" />
                      </div>
                      <h4 className="font-semibold mb-2">故障检测</h4>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li>• 心跳监控</li>
                        <li>• 异常模式识别</li>
                        <li>• 性能异常检测</li>
                        <li>• 依赖服务监控</li>
                      </ul>
                    </div>
                    <div className="text-center">
                      <div className="bg-yellow-100 dark:bg-yellow-900 p-4 rounded-lg mb-4">
                        <RefreshCw className="h-8 w-8 mx-auto text-yellow-600" />
                      </div>
                      <h4 className="font-semibold mb-2">自动恢复</h4>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li>• 智能重试机制</li>
                        <li>• 断路器模式</li>
                        <li>• 服务降级</li>
                        <li>• 状态重建</li>
                      </ul>
                    </div>
                    <div className="text-center">
                      <div className="bg-green-100 dark:bg-green-900 p-4 rounded-lg mb-4">
                        <CheckCircle className="h-8 w-8 mx-auto text-green-600" />
                      </div>
                      <h4 className="font-semibold mb-2">数据一致性</h4>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li>• 事务补偿</li>
                        <li>• 幂等性保证</li>
                        <li>• 状态同步</li>
                        <li>• 数据校验</li>
                      </ul>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="monitoring" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle>性能监控和优化</CardTitle>
                  <CardDescription>
                    全方位的系统监控和性能优化方案
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-6">
                    <div>
                      <h4 className="font-semibold mb-3">实时监控面板</h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-lg">
                          <h5 className="font-medium mb-2">业务指标</h5>
                          <ul className="space-y-1 text-sm">
                            <li>• 支付成功率：99.95%</li>
                            <li>• 平均处理时间：85ms</li>
                            <li>• 当前TPS：45,230</li>
                            <li>• 错误率：0.05%</li>
                          </ul>
                        </div>
                        <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-lg">
                          <h5 className="font-medium mb-2">系统指标</h5>
                          <ul className="space-y-1 text-sm">
                            <li>• CPU使用率：65%</li>
                            <li>• 内存使用率：72%</li>
                            <li>• 网络吞吐：2.1GB/s</li>
                            <li>• 磁盘I/O：450MB/s</li>
                          </ul>
                        </div>
                      </div>
                    </div>
                    <div>
                      <h4 className="font-semibold mb-3">性能优化建议</h4>
                      <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-lg">
                        <ul className="space-y-2 text-sm">
                          <li>
                            • <strong>批处理优化：</strong>
                            将小额支付合并处理，提升吞吐量
                          </li>
                          <li>
                            • <strong>缓存策略：</strong>
                            热点账户信息缓存，减少数据库查询
                          </li>
                          <li>
                            • <strong>分片策略：</strong>
                            按地区或银行分片，提升并行处理能力
                          </li>
                          <li>
                            • <strong>预处理：</strong>非业务时间预加载常用数据
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </section>

      {/* Use Cases */}
      <section className="py-16 px-4 bg-white/50 dark:bg-slate-800/50">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">应用场景</h2>
            <p className="text-lg text-muted-foreground">
              适用于各种实时支付处理需求
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <CreditCard className="h-12 w-12 mx-auto text-blue-600 mb-4" />
                <CardTitle className="text-lg">移动支付</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground mb-4">
                  支持大规模移动支付场景，毫秒级响应
                </p>
                <Badge variant="outline">扫码支付</Badge>
                <Badge variant="outline" className="ml-2">
                  NFC支付
                </Badge>
              </CardContent>
            </Card>

            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <Zap className="h-12 w-12 mx-auto text-yellow-600 mb-4" />
                <CardTitle className="text-lg">即时转账</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground mb-4">
                  银行间实时转账，24/7不间断服务
                </p>
                <Badge variant="outline">跨行转账</Badge>
                <Badge variant="outline" className="ml-2">
                  国际汇款
                </Badge>
              </CardContent>
            </Card>

            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <Activity className="h-12 w-12 mx-auto text-green-600 mb-4" />
                <CardTitle className="text-lg">批量处理</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground mb-4">
                  大批量支付处理，智能优化执行
                </p>
                <Badge variant="outline">工资发放</Badge>
                <Badge variant="outline" className="ml-2">
                  供应商付款
                </Badge>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      {/* Customer Case Studies */}
      <div className="bg-white/50 dark:bg-slate-800/50">
        <CaseStudies
          studies={caseStudiesByIndustry['real-time-payment']}
          title="客户成功案例"
          description="真实的实时支付系统部署案例和业务价值"
        />
      </div>

      {/* CTA Section */}
      <section className="py-20 px-4">
        <div className="max-w-4xl mx-auto text-center">
          <h2 className="text-3xl font-bold mb-6">构建您的实时支付系统</h2>
          <p className="text-lg text-muted-foreground mb-8">
            获取基于CActor的实时支付处理解决方案，实现高性能、高可靠的支付服务
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Button size="lg" className="bg-purple-600 hover:bg-purple-700">
              获取解决方案
            </Button>
            <Button size="lg" variant="outline">
              在线演示
            </Button>
          </div>
        </div>
      </section>

      {/* Solutions Navigation */}
      <div className="max-w-7xl mx-auto px-4">
        <SolutionsNavigationSimple />
      </div>
    </div>
  );
}
